import React, { useState, useEffect, useRef } from 'react';
import {
  Button,
  Modal,
  Form,
  Input,
  Select,
  message,
  InputNumber,
  Popconfirm,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import type { ActionType } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import TableTitle from '@/components/TableTitle';
import { deliverRecordColumnsData } from './data';
import { getDictType } from '@/services/services';
import { getLocalStorageInfo } from '@/utils/localStorageInfo';
import type {
  ThemeItemType,
  DeliverRecordColumnsItem,
  DictItemType,
  ThemeFragmentsItemType,
  CustomerItemType,
  AccountListType,
} from './data';
import {
  getDeliverRecordList,
  getFragmentsByThemeNo,
  getThemeNftList,
  getDeliverRecordInfo,
  getCustomerList,
  addDeliver,
  getAccountCategory,
} from './service';

const { Option } = Select;
const { TextArea } = Input;

const DeliverRecord = () => {
  // 控制添加模态框
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  // 空投物类型表
  const [deliverTypeList, setDeliverTypeList] = useState<
    DictItemType[] | null
  >();
  // 空投物类型编号
  const [deliverType, setDeliverType] = useState<string | null>();
  // 空投主题表
  const [themeList, setThemeList] = useState<ThemeItemType[]>();
  // 空投碎片表
  const [fragmentsList, setFragmentsList] = useState<ThemeFragmentsItemType[]>(
    [],
  );
  // 客户列表
  const [customerList, setCustomerList] = useState<CustomerItemType[]>([]);
  // 客户账户列表
  const [AccountList, setAccountList] = useState<AccountListType[]>([]);

  /**
   * 点击查看
   * @param record 查看的规则对象
   */
  const view = async (record: DeliverRecordColumnsItem) => {
    const { serialNo } = record;
    let res = await getDeliverRecordInfo({ serialNo });
    console.log(res);
  };

  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) => (
    <ul className="ant-list-item-action" style={{ margin: 0 }}>
      <li>
        <a onClick={() => view(record)}>查看</a>
      </li>
    </ul>
  );

  // 绑定表格渲染样式
  deliverRecordColumnsData.forEach((item) => {
    item.dataIndex === 'action' ? (item.render = actionRender) : null;
  });

  /**
   * 点击投放按钮调用
   */
  const addDeliverRecord = async () => {
    console.log('addDeliverRuler');
    getCustomerInfo();
    setIsAddModalVisible(true);
    // 获取空投物类型字典
    let res = await getDictType({
      dictType: 'deliver-type',
      pageSize: 10,
      current: 1,
    });
    if (res.code !== '000000')
      message.info('获取空投物类型选项失败，请检查字典库！');
    setDeliverTypeList(res.data);
  };

  /**
   * 获取客户列表
   * @param nickname 客户昵称
   */
  const getCustomerInfo = async (nickname?: string) => {
    let res = nickname
      ? await getCustomerList({
          nickname,
          pageSize: 50,
          current: 1,
        })
      : await getCustomerList({
          pageSize: 50,
          current: 1,
        });
    if (res.code !== '000000') message.info('获取客户列表失败');
    setCustomerList(res.data);
  };

  /**
   * 搜索客户调用
   * @param nickname 搜索内容
   */
  const searchCustomerNo = (nickname: string) => {
    console.log(nickname);
    getCustomerInfo(nickname);
  };

  /**
   * 获取当前用户账户
   */
  const getAccount = async () => {
    let customerNo = getLocalStorageInfo('customerInfo').customerNo;
    let res = await getAccountCategory({ customerNo });
    console.log(res);
    setAccountList(res.data);
  };

  /**
   * 搜索主题列表
   */
  const getThemeList = async () => {
    let res = await getThemeNftList({
      current: 1,
      pageSize: 100,
    });
    console.log(res);
    setThemeList(res.data);
  };

  /**
   * 空投物类型改变时调用
   */
  const onDeliverTypeChange = async (e: string) => {
    console.log(e);
    setDeliverType(e);
    switch (e) {
      case '1':
        getAccount();
        break;
      case '2':
        getThemeList();
        break;
      case '3':
        getThemeList();
        break;
      default:
        break;
    }
  };

  /**
   * 空投碎片主题改变时调用
   */
  const onThemeChange = async (e: string) => {
    console.log(e);
    let res = await getFragmentsByThemeNo({
      current: 1,
      pageSize: 20,
      serialNo: e,
    });
    console.log(res);
    setFragmentsList(res.data);
  };

  /**
   * 投放配置模态框确定按钮调用
   */
  const handleAddOk = async () => {
    console.log('handleAddOk');
    // 表单验证
    await addFormRef.validateFields();
    let response = addFormRef.getFieldsValue();
    console.log(response);
    let type = Number(response.type);
    let res = await addDeliver({ ...response, type });
    console.log(res);
    deliverRecordActionRef.current?.reload();
    setIsAddModalVisible(false);
  };

  /**
   * 投放配置模态框取消按钮调用
   */
  const handleAddCancel = () => {
    addFormRef.resetFields();
    setIsAddModalVisible(false);
    console.log('handleAddCancel');
  };

  // 绑定表格和搜索表单，方便自定义操作
  const deliverRecordActionRef = useRef<ActionType>();
  const searchFormRef = useRef<ProFormInstance>();
  // 绑定添加规则表单
  const [addFormRef] = Form.useForm();

  return (
    <>
      <ProTable<DeliverRecordColumnsItem>
        // 表格标题
        headerTitle={<TableTitle title="投放记录" />}
        //配置工具栏按钮
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={addDeliverRecord}
          >
            投放
          </Button>,
        ]}
        // 绑定表格
        actionRef={deliverRecordActionRef}
        // 绑定搜索表单
        formRef={searchFormRef}
        // 绑定单元格格式
        columns={deliverRecordColumnsData}
        // 最小宽度
        scroll={{ x: 900 }}
        // 单元格边框显示
        bordered
        // 请求数据
        request={async (params) => {
          console.log(params);
          let res = await getDeliverRecordList({ ...params });
          console.log(res);
          let result = {
            data: [],
            total: 0,
          };
          if (res.code === '000000') {
            result = {
              data: res.data,
              total: res.pagination.totalSize,
            };
          }
          return result;
        }}
        // 本地储存表格列的显示参数
        columnsState={{
          persistenceKey: 'DeliverRecordList',
          persistenceType: 'localStorage',
        }}
        // 每行表格的key
        rowKey="serialNo"
        // 搜索表单布局配置
        search={{
          labelWidth: 'auto',
        }}
        // 分页相关配置
        pagination={{
          // 初始页面数据条数
          pageSize: 10,
        }}
        dateFormatter="string"
      />
      {/* 添加单独投放模态框 */}
      <Modal
        title="添加投放"
        centered
        visible={isAddModalVisible}
        onOk={handleAddOk}
        onCancel={handleAddCancel}
        width={700}
      >
        <Form
          name="basic"
          form={addFormRef}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 12 }}
          autoComplete="off"
        >
          {/* <Form.Item
            label="规则名称"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入规则名称', // 验证失败提示
              },
            ]}
          >
            <Input maxLength={20} />
          </Form.Item> */}
          <Form.Item
            label="规则编码"
            name="airdropRuleNo"
            rules={[
              {
                required: true,
                message: '请输入规则编号', // 验证失败提示
              },
            ]}
          >
            <Input maxLength={20} />
          </Form.Item>
          <Form.Item
            label="获得客户"
            name="customerNo"
            rules={[
              {
                required: true,
                message: '请选择空投客户', // 验证失败提示
              },
            ]}
          >
            <Select showSearch filterOption={false} onSearch={searchCustomerNo}>
              {customerList
                .filter((item) => item.nickname)
                .map((item) => {
                  return (
                    <Option key={item.customerNo} value={item.customerNo}>
                      {item.nickname}
                    </Option>
                  );
                })}
            </Select>
          </Form.Item>
          <Form.Item
            label="投放物"
            name="type"
            rules={[
              {
                required: true,
                message: '请选择投放物', // 验证失败提示
              },
            ]}
          >
            <Select onChange={onDeliverTypeChange}>
              {deliverTypeList?.map((item) => (
                <Option key={item.itemValue} value={item.itemValue}>
                  {item.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          {deliverType == '2' ? (
            <Form.Item
              label="请选择主题"
              name="typeNo"
              rules={[
                {
                  required: true,
                  message: '请选择空投主题', // 验证失败提示
                },
              ]}
            >
              <Select>
                {themeList
                  ?.filter((item) => item.fragmentsFlag == '0')
                  .map((item) => (
                    <Option key={item.serialNo} value={item.serialNo}>
                      {item.themeName}
                      {item.sex == 0 ? '(男)' : null}
                      {item.sex == 1 ? '(女)' : null}
                    </Option>
                  ))}
              </Select>
            </Form.Item>
          ) : null}
          {deliverType == '3' ? (
            <>
              <Form.Item
                label="请选择主题"
                name="themeTypeNo"
                rules={[
                  {
                    required: true,
                    message: '请选择空投主题', // 验证失败提示
                  },
                ]}
              >
                <Select onChange={onThemeChange}>
                  {themeList
                    ?.filter((item) => item.fragmentsFlag == '1')
                    .map((item) => (
                      <Option key={item.serialNo} value={item.serialNo}>
                        {item.themeName}
                        {item.sex == 0 ? '(男)' : null}
                        {item.sex == 1 ? '(女)' : null}
                      </Option>
                    ))}
                </Select>
              </Form.Item>
              <Form.Item
                label="请选择碎片"
                name="typeNo"
                rules={[
                  {
                    required: true,
                    message: '请选择空投碎片', // 验证失败提示
                  },
                ]}
              >
                <Select>
                  {fragmentsList?.map((item) => (
                    <Option key={item.serialNo} value={item.serialNo}>
                      {item.fragmentsSerialNo}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </>
          ) : null}
          <Form.Item
            label="投放数量"
            name="amount"
            rules={[
              {
                required: true,
                message: '请输入积分数量', // 验证失败提示
              },
            ]}
          >
            <InputNumber min={1} />
          </Form.Item>
          {deliverType == '1' ? (
            <Form.Item
              label="请选择币种"
              name="ccy"
              rules={[
                {
                  required: true,
                  message: '请选择空投币种', // 验证失败提示
                },
              ]}
            >
              <Select>
                {AccountList?.map((item) => item.ccy)
                  .filter((item, index, self) => self.indexOf(item) === index)
                  .map((item) => (
                    <Option key={item} value={item}>
                      {item}
                    </Option>
                  ))}
              </Select>
            </Form.Item>
          ) : null}
          <Form.Item
            label="规则描述"
            name="description"
            rules={[
              {
                required: true,
                message: '请选择空投主题', // 验证失败提示
              },
            ]}
          >
            <TextArea />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default DeliverRecord;
